package com.factory.iamp.service.impl;

import com.factory.iamp.dao.RoleMapper;
import com.factory.iamp.dao.UserMapper;
import com.factory.iamp.pojo.Role;
import com.factory.iamp.pojo.RoleBuild;
import com.factory.iamp.service.RoleService;
import com.factory.iamp.utils.exception.APIException;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.helper.ResponseCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional(rollbackFor = Throwable.class)
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserMapper userMapper;

    private void checkMemberList(List<String> member) {
        if(member.size() < 1) throw new APIException(ResponseCode.VALIDATE_FAILED, "成员列表为空");
        if(userMapper.listCount(member) != member.size())
            throw new APIException(ResponseCode.DATABASE_FAILED, "含有错误的用户id");
    }

    @Override
    public int Count() {
        return roleMapper.Count();
    }

    @Override
    public List<Role> ListPaged(PageHelper data) {
        return roleMapper.ListPaged(data.calOffset(), data.getLimit());
    }

    @Override
    public Role findById(int rid) {
        return roleMapper.findById(rid);
    }

    @Override
    public Boolean findByIdName(int rid, String name) {
        return roleMapper.findByIdName(rid, name);
    }

    @Override
    public Role addRole(Role role) throws Throwable {
        if(roleMapper.findByName(role.getName()) != null)
            throw new APIException(ResponseCode.DATABASE_FAILED, "角色已存在");
        HashMap<String, Object> data = new HashMap<>();
        for(Field fields : role.getClass().getDeclaredFields()) {
            if(fields.getName().equals("rid")) continue;
            data.put(fields.getName(), role.ReflectGet(fields.getName()));
        }
        roleMapper.addRole(data);
        return roleMapper.findByName(role.getName());
    }

    @Override
    public void buildRoleUser(RoleBuild roleBuild) {
        checkMemberList(roleBuild.getMember());
        userMapper.buildRoleUser(roleBuild.getRid(), roleBuild.getMember());
    }

    @Override
    public void deleteRole(int rid) {
        if(userMapper.countByRole(rid) > 0)
            throw new APIException(ResponseCode.DATABASE_FAILED, "角色仍存在用户，请先清空用户");
        roleMapper.deleteById(rid);
    }
}
